const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    base_candidate_info: {
      id_number: '',
      phone: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      foreign_language_id: '',
      political_status_id: ''
    },
    ck_academic_info: {
      education_level: '',
      diploma_number: '',
      graduation_type: '',
      graduation_school: '',
      graduation_date: '',
      job_category: '',
      is_working: '',
      work_location: '',
      work_name: '',
      work_start_date: ''
    },
    ck_exam_info: {
      exam_type: '',
      outside_residence: '',
      military_service: '',
      household_location: '',
      candidate_feature: '',
      admission_category: '',
      exam_level: '',
      exam_subject: '',
      study_location: '',
      study_mode: '',
      exam_site_id: '',
      postal_code: '',
      ck_exam_university_school: '',
      ck_major: '',
      emergency_contact: ''
    },
    exam_site_info: {
      code: '',
      name: '',
      address: ''
    },
    expanded: {
      base: false,
      academic: false,
      exam: false
    },
    idToNameMappings: {
      ethnicity: {},         // 民族映射
      politicalstatus: {},   // 政治面貌映射
      foreignlanguage: {},  // 外语语种映射
      CKeducation: {},
      graduationType: {},
      CKoccupation: {},
      CKschool: {},
      examType: {},
      outsideResidence: {},
      militaryService: {},
      candidateFeature: {},
      admissionCategory: {},
      examLevel: {},
      examSubject: {},
      studyLocation: {},
      studyMode: {},
      examUniversity: {},
      CKMajor: {}
    }
  },
  formatDate(dateString) {
    if (!dateString) return '';

    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
  },
  async onLoad() {
    try {
      const baseInfo = wx.getStorageSync('base_candidate_info');
      let academicInfo = wx.getStorageSync('ck_academic_info') || {};
      let examInfo = wx.getStorageSync('ck_exam_info') || {};

      if (baseInfo) {
        baseInfo.birth_date = this.formatDate(baseInfo.birth_date);
        this.setData({ base_candidate_info: baseInfo });
      }

      if(JSON.stringify(academicInfo) === '{}'){
        await tools.loadExamInfo(baseInfo.id_number);
        academicInfo = wx.getStorageSync('ck_academic_info')||{};
        examInfo = wx.getStorageSync('ck_exam_info')||{};
      }

      this.setData({
        base_candidate_info:baseInfo,
        ck_academic_info: academicInfo,
        ck_exam_info: examInfo,
      })
      await this.fetchNameMappings();
    } catch (error) {
      console.error('Error loading candidate info from storage:', error);
    }
  },
  fetchNameMappings() {
    const mappingFields = {
      ethnicity: 'ethnicity_id',         // 民族
      politicalstatus: 'political_status_id',   // 政治面貌
      foreignlanguage: 'foreign_language_id',  // 外语语种
      CKeducation: 'education_level',
      graduationType: 'graduation_type',
      CKoccupation: 'job_category',
      CKschool: 'graduation_school',
      examType: 'exam_type',
      outsideResidence: 'outside_residence',
      militaryService: 'military_service',
      candidateFeature: 'candidate_feature',
      admissionCategory: 'admission_category',
      examLevel: 'exam_level',
      examSubject: 'exam_subject',
      studyLocation: 'study_location',
      studyMode: 'study_mode',
      examUniversity: 'ck_exam_university_school',
      CKMajor: 'ck_major'
    };

    const promises = [];
    // 单独处理地址信息
    promises.push(
      http.get(`/chengkao/examSite/${this.data.ck_exam_info.exam_site_id}`).then(res =>{
        this.setData({exam_site_info:res.data.data})
      })
    )

    Object.keys(mappingFields).forEach((field) => {
      const fieldId = mappingFields[field];
      const ids = this.getUniqueIds(fieldId);

      if (ids.length === 0) return;

      ids.forEach((id) => {
        let url = '';
        if (field === 'ethnicity') {
          url = `/ethnicity/info?id=${id}`; // 民族特殊处理
        } else if (field === 'politicalstatus') {
          url = `/politicalstatus/info?id=${id}`; // 政治面貌特殊处理
        } else if (field === 'foreignlanguage') {
          url = `/foreignlanguage/info?id=${id}`; // 外语语种特殊处理
        } else {
          url = `/chengkao/${field}/${id}`; // 其他字段通用处理
        }
        promises.push(
          http.get(url).then((res) => {
            if (res.statusCode === 200) {
              const newName = res.data.data.name || '未知';
              this.setData({
                [`idToNameMappings.${field}.${id}`]: newName
              });
            } else {
              console.error(`Error fetching ${field} info for id ${id}:`, res.data.message);
            }
          }).catch((err) => {
            console.error(`Error fetching ${field} info for id ${id}:`, err);
          })
        );
      });
    });

    return Promise.all(promises).catch((err) => {
      console.error('Error fetching all mappings:', err);
    });
  },
  getUniqueIds(fieldId) {
    const ids = new Set();
    const { base_candidate_info, ck_academic_info, ck_exam_info } = this.data;

    [base_candidate_info, ck_academic_info, ck_exam_info].forEach((info) => {
      if (info[fieldId]) {
        ids.add(info[fieldId]);
      }
    });

    return Array.from(ids);
  },
  getExamSiteInfo(siteId) {
    http.get(`/chengkao/examSite/${siteId}`).then((res) => {
      if (res.statusCode === 200) {
        this.setData({
          exam_site_info: {
            code: res.data.data.code || '',
            name: res.data.data.name || '',
            address: res.data.data.address || ''
          }
        });
      } else {
        console.error(`Error fetching exam site info for id ${siteId}:`, res.data.message);
      }
    }).catch((err) => {
      console.error(`Error fetching exam site info for id ${siteId}:`, err);
    });
  },
  toggleSection(e) {
    const { section } = e.currentTarget.dataset;
    this.setData({
      [`expanded.${section}`]: !this.data.expanded[section]
    });
  },
  navigateToEdit(e) {
    const { section } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/chengkao/chengkao_page${section}/chengkao_page${section}`
    });
  }
});